package cn.zcscloud.mall.controller;

import cn.hutool.core.collection.CollUtil;
import cn.zcscloud.mall.common.PageRequest;
import cn.zcscloud.mall.common.R;
import cn.zcscloud.mall.mbg.dto.ProductAttributeDto;
import cn.zcscloud.mall.mbg.mapper.PmsProductAttributeCategoryMapper;
import cn.zcscloud.mall.mbg.mapper.PmsProductAttributeMapper;
import cn.zcscloud.mall.mbg.model.PmsProductAttribute;
import cn.zcscloud.mall.mbg.model.PmsProductAttributeCategory;
import cn.zcscloud.mall.mbg.model.PmsProductCategoryAttributeRelation;
import cn.zcscloud.mall.service.PmsProductAttributeCategoryService;
import cn.zcscloud.mall.service.PmsProductAttributeService;
import cn.zcscloud.mall.service.PmsProductCategoryAttributeRelationService;
import cn.zcscloud.mall.service.PmsProductCategoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 根据商品分类的id获取商品属性及属性分类
 */
@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/productAttribute")
public class PmsProductAttributeController {

    @Autowired
    private PmsProductAttributeService pmsProductAttributeService;

    @Autowired
    private PmsProductAttributeCategoryService pmsProductAttributeCategoryService;

    @Autowired
    private PmsProductCategoryService pmsProductCategoryService;

    @Autowired
    private PmsProductAttributeMapper pmsProductAttributeMapper;

    @Autowired
    private PmsProductAttributeCategoryMapper pmsProductAttributeCategoryMapper;

    @Autowired
    private PmsProductCategoryAttributeRelationService pmsProductCategoryAttributeRelationService;

    @GetMapping("/list/{cid}")
    public R attrInfo(@PathVariable Integer cid, Integer type, Integer pageNum, Integer pageSize) {
        log.info("Integer cid = {}, Integer type = {},Integer pageNem ={},Integer pageSize = {}", cid, type, pageNum, pageSize);
        Page<PmsProductAttribute> objectPage = new Page<>(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize);

        LambdaQueryWrapper<PmsProductAttribute> lqw = new LambdaQueryWrapper<>();
        lqw.eq(PmsProductAttribute::getProductAttributeCategoryId, cid)
                .eq(PmsProductAttribute::getType, type);
        IPage<PmsProductAttribute> page = pmsProductAttributeService.page(objectPage, lqw);
        return R.success("操作成功", PageRequest.init(page));

    }

    @GetMapping("/category/list")
    public R list(String keyword, int pageNum, int pageSize) {

        LambdaQueryWrapper<PmsProductAttributeCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(keyword != null, PmsProductAttributeCategory::getName, keyword);

        Page<PmsProductAttributeCategory> page = new Page<>(pageNum, pageSize);

        pmsProductAttributeCategoryService.page(page, queryWrapper);


        return R.success("操作成功", PageRequest.init(page));
    }

    @PostMapping("/category/create")
    public R creat(String name) {
        log.info("name就是：{}", name);

        PmsProductAttributeCategory pmsProductAttributeCategory = new PmsProductAttributeCategory();
        pmsProductAttributeCategory.setAttributeCount(0);
        pmsProductAttributeCategory.setName(name);
        pmsProductAttributeCategory.setParamCount(0);

        pmsProductAttributeCategoryService.save(pmsProductAttributeCategory);

        return R.success("操作成功", null);
    }

    /**
     * Description: 更新商品类型名称
     *
     * @author: zjf95
     * @date: 2022/4/2 10:22
     * @param:
     * @return:
     */
    @PostMapping("/category/update/{id}")
    public R update(@PathVariable Integer id, String name) {
        if (id == null) {
            return R.error("数据有误");
        }
        LambdaQueryWrapper<PmsProductAttributeCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(name != null, PmsProductAttributeCategory::getName, name);
        PmsProductAttributeCategory category = pmsProductAttributeCategoryService.getOne(queryWrapper);
        if (category == null) {
            PmsProductAttributeCategory productAttributeCategory = pmsProductAttributeCategoryService.getById(id);

            productAttributeCategory.setName(name);
            pmsProductAttributeCategoryService.updateById(productAttributeCategory);

            return R.success("操作成功", null);
        } else {
            return R.error("该数据已存在");
        }
    }

    @GetMapping("/{id}")
    public R One(@PathVariable Integer id) {

        PmsProductAttribute productAttribute = pmsProductAttributeService.getById(id);
        if (productAttribute == null) {
            return R.error("数据失败");
        }
        return R.success("操作成功", productAttribute);
    }

    /**
     * Description:修改属性或者参数
     *
     * @author: zjf95
     * @date: 2022/4/3 11:11
     * @param:
     * @return:
     */
    @PostMapping("/update/{id}")
    public R update(@PathVariable Integer id, @RequestBody PmsProductAttribute productAttribute) {
        log.info("修改的id为：{}", id);
        log.info("传输过来的数据为：{}", productAttribute);

        PmsProductAttribute pmsProductAttribute = pmsProductAttributeService.getById(id);

        //修改前的商品类型id
        Long attributeCategoryId = pmsProductAttribute.getProductAttributeCategoryId();

        //修改后的商品类型id
        Long productAttributeCategoryId = productAttribute.getProductAttributeCategoryId();

        if (pmsProductAttribute == null) {
            return R.error("该数据不存在");
        }
        //BeanUtils.copyProperties(productAttribute, pmsProductAttribute);

        //商品类型一致的时候就只用修改一次
        pmsProductAttributeService.updateById(productAttribute);
        updateProductAttributeCategoryCount(attributeCategoryId);

        //不一致就修改两次
        if (!Objects.equals(productAttributeCategoryId, attributeCategoryId)) {
            updateProductAttributeCategoryCount(productAttributeCategoryId);
        }

        return R.success("操作成功", null);
    }

    //创建
    @PostMapping("/create")
    public R create(@RequestBody PmsProductAttribute pmsProductAttribute) {

        log.info("前端传输的要添加的数据为：{}", pmsProductAttribute);

        if (pmsProductAttribute != null) {
            pmsProductAttributeService.save(pmsProductAttribute);
        }

        Long productAttributeCategoryId = pmsProductAttribute.getProductAttributeCategoryId();
        Integer type = pmsProductAttribute.getType();
        LambdaQueryWrapper<PmsProductAttributeCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(productAttributeCategoryId != null, PmsProductAttributeCategory::getId, productAttributeCategoryId);

        PmsProductAttributeCategory productAttributeCategory = pmsProductAttributeCategoryService.getOne(queryWrapper);

        if (productAttributeCategory == null) {
            return R.error("我是异常的异常");
        }
        //表示这个是属性
        if (type == 0) {
            Integer attributeCount = productAttributeCategory.getAttributeCount();
            attributeCount++;
            productAttributeCategory.setAttributeCount(attributeCount);
        } else {
            //表示参数
            Integer paramCount = productAttributeCategory.getParamCount();
            paramCount++;
            productAttributeCategory.setParamCount(paramCount);
        }
        pmsProductAttributeCategoryService.updateById(productAttributeCategory);

        return R.success("操作成功", null);
    }

    //修改商品类型的属性或者参数的数量
    public void updateProductAttributeCategoryCount(Long attributeCategoryId) {
        PmsProductAttributeCategory pmsProductAttributeCategory = new PmsProductAttributeCategory();
        Integer attributeCountNum = pmsProductAttributeMapper.selectByIdAttributeCountNum(attributeCategoryId);
        Integer paramCountNum = pmsProductAttributeMapper.selectByIdParamCountNum(attributeCategoryId);
        pmsProductAttributeCategory.setId(attributeCategoryId);
        pmsProductAttributeCategory.setAttributeCount(attributeCountNum);
        pmsProductAttributeCategory.setParamCount(paramCountNum);
        pmsProductAttributeCategoryMapper.updateById(pmsProductAttributeCategory);
    }

    /**
     * Description: 删除相应的商品，这个需要注意的是需要同时删除对应的属性或者参数里面的数据
     *
     * @author: zjf95
     * @date: 2022/4/2 21:50
     * @param:
     * @return:
     */
    @GetMapping("/category/delete/{id}")
    public R delete(@PathVariable Long id) {

        LambdaQueryWrapper<PmsProductAttribute> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(id != null, PmsProductAttribute::getProductAttributeCategoryId, id);

        pmsProductAttributeService.remove(queryWrapper);

        pmsProductAttributeCategoryService.removeById(id);
        //List<PmsProductAttribute> list = pmsProductAttributeService.list(queryWrapper);

        //List<Long> ids = CollUtil.getFieldValues(list, "id", Long.class);

        return R.success("操作成功", null);

    }

    /**
     * Description: 批量删除属性或者参数
     * 需要注意的是这个删除之后对应的product表里面的数据需要进行相应的减少
     *
     * @author: zjf95
     * @date: 2022/4/2 21:48
     * @param:
     * @return:
     */
    @PostMapping("/delete")
    public R deleteCategory(@RequestParam List<Long> ids) {
        if (ids.size() == 0 || ids == null) {
            return R.error("数据错误");
        }

        //获取attribute的id集合

        //根据id来删除
        pmsProductAttributeService.removeByIds(ids);

        //通过id来获取对象，然后查询出对应的类型，根据相应的类型来修改数据
        Long id = ids.get(0);
        PmsProductAttribute productAttribute = pmsProductAttributeService.getById(id);
        Integer type = productAttribute.getType();
        Long productAttributeCategoryId = productAttribute.getProductAttributeCategoryId();

        PmsProductAttributeCategory productAttributeCategory = pmsProductAttributeCategoryService
                .getById(productAttributeCategoryId);

        if (type == 0) {
            //表明这是属性
            Integer attributeCount = productAttributeCategory.getAttributeCount();
            attributeCount--;
            productAttributeCategory.setAttributeCount(attributeCount);
        } else {
            //参数
            Integer paramCount = productAttributeCategory.getParamCount();
            paramCount--;
            productAttributeCategory.setParamCount(paramCount);
        }
        pmsProductAttributeCategoryService.updateById(productAttributeCategory);

        return R.success("操作成功", null);

    }

    @GetMapping("/category/list/withAttr")
    public R withAttr() {
        //获取PmsProductAttributeCategory的集合
        List<PmsProductAttributeCategory> list = pmsProductAttributeCategoryService.list();

        //获取productAttributeCategoryId，然后根据这个数据查询productAttribute表
        List<Long> productAttributeCategoryIds = CollUtil.getFieldValues(list, "id", Long.class);

        Map map = pmsProductAttributeService.getByCids(productAttributeCategoryIds);

        List<ProductAttributeDto> dtoList = list.stream().map((item) -> {
            ProductAttributeDto dto = new ProductAttributeDto();
            dto.setName(item.getName());
            List<PmsProductAttribute> o = (List<PmsProductAttribute>) map.get(item.getId());
            if (o == null){
                dto.setProductAttributeList(new ArrayList<>());
            }
            dto.setProductAttributeList(o);
            return dto;
        }).collect(Collectors.toList());

        return R.success("操作成功", dtoList);
    }

    @GetMapping("/attrInfo/{productCategoryId}")
    public R info(@PathVariable Integer productCategoryId){

        log.info("属性id：{}",productCategoryId);

        LambdaQueryWrapper<PmsProductCategoryAttributeRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(productCategoryId != null,
                PmsProductCategoryAttributeRelation::getProductCategoryId,productCategoryId);

        List<PmsProductCategoryAttributeRelation> list = pmsProductCategoryAttributeRelationService.list(queryWrapper);


        if (CollUtil.isEmpty(list)){
            return R.success("操作成功",new ArrayList<>());
        }
        return R.success(null,list);
    }

}
